<template>
  <div class="payHistory">
    <div class="header">
      <van-popover v-model:show="showPopover" :actions="actions" @select="onSelect">
        <template #reference>
          <span style="font-size: 14px;color:black;">{{ defaultSel }}<van-icon name="play" /></span>
        </template>
      </van-popover>
      <div class="total_amount">
        <span>累计金额:</span>
        <span style="font-weight: 900;color: black;">￥</span>
        <span style="font-weight: 900;font-size: 16px;color: black;">{{ totalMount.toLocaleString('en-US', {
          minimumFractionDigits: 2, maximumFractionDigits: 2
        }) }}</span>
      </div>
    </div>
    <div>
      <div v-if="recordList.length > 0">
        <PayHistoryItem v-for="item in recordList" :data="item"></PayHistoryItem>
      </div>
      <div v-if="loading" style="padding: 20px 0;">
        <van-skeleton title row="3" />
        <van-skeleton title row="3" />
        <van-skeleton title row="3" />
        <van-skeleton title row="3" />
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { onMounted, ref } from 'vue';
import PayHistoryItem from '../payHistoryItem/payHistoryItem.vue';
import { fetchPayRecord, fetchPayTotal } from '@/api/pay';
import { IAction, IUnPay } from '../../type';

const curYear = new Date().getFullYear()

const showPopover = ref(false);
const totalMount = ref(0)
const defaultSel = ref(String(curYear));
const loading = ref(true)
// 通过 actions 属性来定义菜单选项
const actions = [0, 1, 2].map(val => {
  return {
    text: String(curYear - val),
    value: val
  }
})
const recordList = ref<IUnPay[]>([]);
async function getPayRecord() {
  try {
    let res = await fetchPayRecord({
      token: '',
      year: defaultSel.value
    });
    if (res.code === 200)
      recordList.value = res.data as IUnPay[];
    totalMount.value = recordList.value.reduce<number>((prev, cur) => {
      return Number(prev + Number(cur.realitycostMoney));
    }, 0)

  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
async function getTotalAmount() {
  let res = await fetchPayTotal({
    token: '',
    year: defaultSel.value
  });
  if (res.code === 200)
    totalMount.value = res.data;
}
onMounted(() => {
  getPayRecord();
  // getTotalAmount()
})
const onSelect = (action: IAction) => {
  defaultSel.value = action.text
  getPayRecord();
  getTotalAmount();
};

</script>

<style lang='less' scoped>
.payHistory {
  padding: 10px 17.2px;
  background-color: #f4f7fa;
  height: 100%;
  overflow-y: auto;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .van-badge__wrapper {
      transform: rotate(90deg) scale(0.7);
    }
  }
}
</style>
<style lang="less">
.van-skeleton {
  margin-bottom: 10px;
}
</style>